package teacher;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Enumeration;

@WebServlet("/ExamApplyServlet")
@MultipartConfig // 添加这个注解来处理 multipart/form-data
public class ExamApplyServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Integer teacherId = (Integer) session.getAttribute("teacher_id");

        // 设置响应类型为JSON
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        // 创建JSON响应对象
        java.util.Map<String, Object> jsonResponse = new java.util.HashMap<>();

        if (teacherId == null) {
            jsonResponse.put("success", false);
            jsonResponse.put("message", "会话已过期，请重新登录");
            out.print(mapToJson(jsonResponse));
            return;
        }

        // 调试：打印所有参数名
        System.out.println("Received parameter names:");
        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            System.out.println(paramName + ": " + request.getParameter(paramName));
        }

        // 获取参数
        String examName = getParameterValue(request, "exam-name");
        String courseIdStr = getParameterValue(request, "exam-course");
        String[] classIds = request.getParameterValues("exam-class");
        String examDate = getParameterValue(request, "exam-date");
        String examTime = getParameterValue(request, "exam-time");
        String durationStr = getParameterValue(request, "exam-duration");
        String description = getParameterValue(request, "exam-description");

        // 调试日志 - 打印所有参数
        System.out.println("Received parameters:");
        System.out.println("exam-name: " + examName);
        System.out.println("exam-course: " + courseIdStr);
        System.out.println("exam-date: " + examDate);
        System.out.println("exam-time: " + examTime);
        System.out.println("exam-duration: " + durationStr);
        System.out.println("exam-classes: " + (classIds != null ? String.join(",", classIds) : "null"));
        System.out.println("exam-description: " + description);

        // 验证必填字段
        if (isEmpty(examName) || isEmpty(courseIdStr) ||
                isEmpty(examDate) || isEmpty(examTime) ||
                isEmpty(durationStr) || classIds == null || classIds.length == 0) {

            jsonResponse.put("success", false);
            jsonResponse.put("message", "缺少必填参数");
            out.print(mapToJson(jsonResponse));
            return;
        }

        int courseId, duration;
        try {
            courseId = Integer.parseInt(courseIdStr);
            duration = Integer.parseInt(durationStr);
        } catch (NumberFormatException e) {
            jsonResponse.put("success", false);
            jsonResponse.put("message", "参数格式错误: " + e.getMessage());
            out.print(mapToJson(jsonResponse));
            return;
        }

        // 合并日期和时间
        String examDateTime = examDate + " " + examTime + ":00";

        Connectmysql conn = null;
        try {
            conn = new Connectmysql(
                    "jdbc:mysql://localhost:3306/exam",
                    "root",
                    "root",
                    "com.mysql.cj.jdbc.Driver"
            );

            if (conn.open()) {
                // 插入考试申请
                String examSql = "INSERT INTO exam (exam_name, course_id, teacher_id, duration, start_time, end_time, " +
                        "apply_time, status, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

                // 解析考试开始时间
                Timestamp startTime = Timestamp.valueOf(examDateTime);
                // 计算结束时间
                Timestamp endTime = new Timestamp(startTime.getTime() + duration * 60000L);
                Timestamp applyTime = new Timestamp(new Date().getTime());

                Object[] examParams = {
                        examName, courseId, teacherId, duration, startTime, endTime,
                        applyTime, 0, description
                };

                int examResult = conn.executeSqlUpdate(examSql, examParams);

                if (examResult > 0) {
                    // 获取刚插入的考试ID
                    ResultSet rs = conn.executeSql("SELECT LAST_INSERT_ID()", new Object[]{});
                    int examId = 0;
                    if (rs.next()) {
                        examId = rs.getInt(1);
                    }

                    // 插入考试班级关联
                    boolean classSuccess = true;
                    StringBuilder classErrors = new StringBuilder();
                    if (classIds != null && classIds.length > 0 && examId > 0) {
                        for (String classId : classIds) {
                            try {
                                int classIdInt = Integer.parseInt(classId);
                                String classSql = "INSERT INTO exam_class (exam_id, class_id) VALUES (?, ?)";
                                conn.executeSqlUpdate(classSql, new Object[]{examId, classIdInt});
                            } catch (NumberFormatException e) {
                                classSuccess = false;
                                classErrors.append("班级ID格式错误: ").append(classId).append("; ");
                            }
                        }
                    }

                    if (classSuccess) {
                        jsonResponse.put("success", true);
                        jsonResponse.put("message", "考试申请提交成功");
                    } else {
                        jsonResponse.put("success", false);
                        jsonResponse.put("message", "部分班级添加失败: " + classErrors.toString());
                    }
                } else {
                    jsonResponse.put("success", false);
                    jsonResponse.put("message", "考试申请提交失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResponse.put("success", false);
            jsonResponse.put("message", "数据库错误: " + e.getMessage());
        } finally {
            if (conn != null) {
                conn.close();
            }
            out.print(mapToJson(jsonResponse));
            out.flush();
        }
    }

    // 辅助方法：检查字符串是否为空
    private boolean isEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }

    // 辅助方法：安全获取参数值
    private String getParameterValue(HttpServletRequest request, String paramName) {
        String value = request.getParameter(paramName);
        return value != null ? value : "";
    }

    // 将Map转换为JSON字符串
    private String mapToJson(java.util.Map<String, Object> map) {
        StringBuilder json = new StringBuilder("{");
        boolean first = true;

        for (java.util.Map.Entry<String, Object> entry : map.entrySet()) {
            if (!first) {
                json.append(",");
            }
            first = false;

            json.append("\"")
                    .append(entry.getKey())
                    .append("\":");

            if (entry.getValue() instanceof String) {
                json.append("\"")
                        .append(entry.getValue().toString().replace("\"", "\\\""))
                        .append("\"");
            } else if (entry.getValue() instanceof Boolean) {
                json.append(entry.getValue());
            } else {
                json.append("\"")
                        .append(entry.getValue().toString())
                        .append("\"");
            }
        }

        json.append("}");
        return json.toString();
    }
}